package filetransfer;

import java.io.*;
import java.net.*;

public class FileReciever extends Thread{
    private String SavePath = "C:\\";
    
    public void run()
    {
        try
        {
            ServerSocket serverSocket = null;
            try {
                serverSocket = new ServerSocket(8191);  
                int bytesRead = 0;
                Socket clientSocket = null; 
                DataInputStream clientData = null;
                OutputStream output = null;
                
                while(true) {  
                    try
                    {
                        clientSocket = serverSocket.accept();  

                        clientData = new DataInputStream(clientSocket.getInputStream());   

                        String fileName = SavePath + '\\' + clientData.readUTF();     
                        output = new FileOutputStream(fileName);     
                        long size = clientData.readLong();     
                        byte[] buffer = new byte[1024];     
                        while (size > 0 && (bytesRead = clientData.read(buffer, 0, (int)Math.min(buffer.length, size))) != -1)     
                        {     
                            output.write(buffer, 0, bytesRead);     
                            size -= bytesRead;     
                        }
                    }
                    catch (IOException ex) 
                    {
                        ex.printStackTrace();
                    }
                    finally
                    {
                        clientData.close();
                        if(output != null) 
                        {
                            output.close();
                        }
                        clientSocket.close();
                    }
                }
            } 
            catch (IOException ex) 
            {
                ex.printStackTrace();
            }
            finally
            {
                serverSocket.close();
            }
        }
        catch (IOException ex) {
	    ex.printStackTrace();
	}
    }
}